//
//  TPQQ.swift
//  sonic
//
//  Created by 魔码传媒 on 2017/06/19.
//  Copyright © 2017年 magicode. All rights reserved.
//

import UIKit
import Foundation
import HandyJSON
import Locksmith

class TPQQ: NSObject,TencentSessionDelegate
{
    static var tencentOAuth:TencentOAuth!
    static var qqPermissions:NSArray!
    
    func setup()
    {
        if TPQQ.tencentOAuth == nil//1105253955
        {
            TPQQ.tencentOAuth = TencentOAuth.init(appId: SRef.Const(const: .qq_key), andDelegate: self)
            TPQQ.qqPermissions = [kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,kOPEN_PERMISSION_ADD_SHARE]
            //["get_user_info", "add_share"]
        }
    }
    
    static func login()
    {
        DispatchQueue.global().async {
            DispatchQueue.main.async
                {
                    TPQQ.tencentOAuth?.authorize(self.qqPermissions as! [Any]!, inSafari: false)
            }
        }
    }
    
    static func installed() -> Bool
    {
        return TencentOAuth.iphoneQQInstalled()
    }
    
    static func shareTo(friend:Bool,title:String,img:String)
    {
        DispatchQueue.global().async {
            DispatchQueue.main.async
                {
                    TPQQ.shareToFriend(title: title, image: img)
            }
        }
    }
    
    static func shareToFriend(title:String,image:String)
    {
//        let utf8String = CommonShare.GenerateUrl(type, eid: "000")
//        let title = title
//        let previewImageUrl = image
//        let newsObj = QQApiNewsObject.object(with: URL.init(string: utf8String), title: title, description: nil, previewImageURL: URL.init(string: previewImageUrl))
//        let req = SendMessageToQQReq.init(content: newsObj as! QQApiObject)
//        QQApiInterface.send(req)
        
//        let filePath =  Bundle.main.path(forResource: "logo", ofType: "png")
        let imgData = NSData(contentsOfFile:image)
        let imgObj = QQApiImageObject(data: imgData as Data!, previewImageData: imgData as Data!,
                                      title: "影响", description: "截图分享")
        let req = SendMessageToQQReq(content: imgObj)
        QQApiInterface.send(req)
    }
    
    static func shareToFriend(type:ShareType,title:String,image:String)
    {
        let utf8String = CommonShare.GenerateUrl(type, eid: "000")
        let title = title
        let previewImageUrl = image
        let newsObj = QQApiNewsObject.object(with: URL.init(string: utf8String), title: title, description: nil, previewImageURL: URL.init(string: previewImageUrl))
        let req = SendMessageToQQReq.init(content: newsObj as! QQApiObject)
        QQApiInterface.send(req)
    }
    
    static func shareToQZone(type:ShareType,title:String,image:String)
    {
        let utf8String = CommonShare.GenerateUrl(type, eid: "000")
        let title = title
        let previewImageUrl = image
        let newsObj = QQApiNewsObject.object(with: URL.init(string: utf8String), title: title, description: nil, previewImageURL: URL.init(string: previewImageUrl))
        let req = SendMessageToQQReq.init(content: newsObj as! QQApiObject)
        QQApiInterface.sendReq(toQZone: req)
    }
    
    /**
     * qq登录成功后的回调
     */
    func tencentDidLogin()
    {
        NSLog("qq登录完成")
        if((TPQQ.tencentOAuth.accessToken != nil) && 0 != TPQQ.tencentOAuth.accessToken.characters.count)
        {
            // 记录登录用户的OpenID、Token以及过期时间
            UserDefaults.standard.set(TPQQ.tencentOAuth.accessToken, forKey: SeThirdKeyQQ_Token)
            UserDefaults.standard.set(TPQQ.tencentOAuth.openId, forKey: SeThirdKeyQQ_OpenId)
            UserDefaults.standard.set(TPQQ.tencentOAuth.expirationDate, forKey: SeThirdKeyQQ_ExpirationDate)
            
            TPQQ.tencentOAuth.getUserInfo()
        }
        else
        {
            NSLog("登录不成功 没有获取accesstoken")
        }
    }
    
    /* QQ获取用户信息 成功回调 这是最终的登录成功回调*/
    func getUserInfoResponse(_ response: APIResponse!)
    {
        NSLog("respons.jsonResponse:%@",response.jsonResponse)
        
        let qq = JSONDeserializer<QQs>.deserializeFrom(dict: response.jsonResponse! as NSDictionary)
        
        let token = UserDefaults.standard.object(forKey: SeThirdKeyQQ_Token) as! String
        let id = UserDefaults.standard.object(forKey: SeThirdKeyQQ_OpenId) as! String
//        let date = UserDefaults.standard.object(forKey: SeThirdKeyQQ_ExpirationDate) as! String
        
        do{
            try Locksmith.updateData(data: [Key_User_State: Value_User_State_QQ,
                                        Key_User_Id: id as Any,
                                        Key_User_Name: qq?.nickname as Any,
                                        Key_User_Token: token as Any,
//                                        Key_User_Token_Refresh_Time: date as Any,
                                        Key_User_Head_Path: qq?.figureurl_2 as Any
            ], forUserAccount: Key_User_Account)
        }
        catch let error
        {
            print("保存蛋疼用户信息时出错: \(error)")
            return
        }
        
        _homeModule?.requestLoadUserData("qq")
        
        //这里开放个代理，完成后调用
    }
    
    /**
     * qq登录失败后的回调
     *     param cancelled 代表用户是否主动退出登录
     */
    func tencentDidNotLogin(_ cancelled: Bool)
    {
        if (cancelled)
        {
            NSLog("用户取消登录")
        }
        else
        {
            NSLog("登录失败")
        }
    }
    
    /**
     * qq登录时网络有问题的回调
     */
    func tencentDidNotNetWork()
    {
        //无网络连接，请设置网络
        NSLog("无网络链接，请设置网络");
    }
    
    
}
